<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

require_once  __DIR__ . '/includes/authenticate.php';

include_once __DIR__ . '/db_bb_connect.php';

include __DIR__ . '/mainpage.php';

?>

<div id="tagging">

<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-md-3"></div>
<div class="col-lg-6 col-md-6"> 

  <h3 align="center">Video Tagging</h3>

<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>" id="form"> 
SELECT season:<br/>
 <select name="season" class="form-control" id="select1" onchange="this.form.submit()">

 <?php if (isset($_POST['season'])) {

 $season = $_POST['season'];
  echo "<option id=\"selected-season\" value=\"$season\" selected=\"selected\">$season is selected</option>";
  
 } else {
  echo "<option id=\"selected-season\" value=\"\" disabled=\"disabled\" selected=\"selected\">Select a season</option>";
 }

 ?>
 
         
<?php

$sql = "SELECT DISTINCT season FROM games ORDER BY season";

$result = $db->query ($sql);

while ($row = $result->fetch_assoc()) {

  if ($row['season'] >= '2018/2019') {
    
    $season = $row['season'];
    echo "<option value=\"$season\"> $season </option>";
  }
  
}
?>
  </select>
<br/>


<?php if (isset($_POST['season'])) { 

$season = $_POST['season']; ?>

SELECT Game: <br/>

<select name="gamenumber" class="form-control" id="select2" onchange="this.form.submit()">

<?php if (isset($_POST['gamenumber'])) {

  $season = $_POST['season'];
  $gamenumber = $_POST['gamenumber'];
  
  echo "<option id=\"selected-game\" value=\"$gamenumber\" selected=\"selected\">Game $gamenumber is selected</option>";
  
 } else {
  echo "<option id=\"selected-game\" value=\"\" disabled=\"disabled\" selected=\"selected\">Select a game</option>";
 } ?>

<?php 
$sql = "SELECT gamenumber, date, opponent, location
FROM games
WHERE season = '$season'
AND NOT embed_code = ''
ORDER BY date DESC";

$result=$db->query($sql);

while($row=$result->fetch_assoc()){ 

    $gamenumber = $row['gamenumber'];
    $date = $row['date'];
    $opponent = $row['opponent'];
    $location = $row['location'];

  echo "<option value='$gamenumber'>Game $gamenumber $date ($opponent $location)  </option>";
}

?>

</select>

<?php } ?>

</form>

 </div>
<div class="col-lg-3 col-md-3"></div>
</div>
</div>

<?php if (isset($_POST['season']) && isset($_POST['gamenumber'])) {
 
$season = $_POST['season'];
$gamenumber = $_POST['gamenumber'];

/// GET YOUTUBE EMBED CODE ///

$sql = "SELECT embed_code, opponent FROM games WHERE season = '$season' AND gamenumber = '$gamenumber'";

$result = $db->query($sql);
$row = $result->fetch_assoc();
$youtubeID = $row['embed_code'];
$opponent_teamname = $row['opponent'];

/// CREATE PLAYERS LIST ///

$sql = "SELECT users.user_key, users.firstname, users.type, users.lastname, teams.playernumber
FROM users 
JOIN teams
ON users.user_key = teams.playerID
WHERE 
(users.type = 'Player' OR users.type = 'Team')  
AND teams.season = '$season'
ORDER BY teams.playernumber";

$result = $db->query($sql);

$players = "";

while( $row = $result->fetch_assoc()){ 

  $user_key = $row['user_key']; 
  $lastname = $row['lastname']; 
  $firstname = $row['firstname']; 
  $playernumber = $row['playernumber'];

  $players .= "{ value: \"$user_key\", label: \"$playernumber $firstname $lastname\" },";

  }

/// ADD OPPONENT PLAYERS LIST ///

$sql = "SELECT teamID FROM teams_list WHERE teamname = '$opponent_teamname'";

$result = $db->query($sql);
$row = $result->fetch_assoc();

$opponent_teamID = $row['teamID']; 

$sql = "SELECT users.user_key, users.firstname, users.type, users.lastname, teams_opponents.playernumber
FROM users 
JOIN teams_opponents
ON users.user_key = teams_opponents.playerID
WHERE 
(users.type = 'Player' OR users.type = 'Team')  
AND teams_opponents.season = '$season'
AND teams_opponents.teamID = '$opponent_teamID'
ORDER BY teams_opponents.playernumber";

$result = $db->query($sql);

while( $row = $result->fetch_assoc()){ 

  $user_key = $row['user_key']; 
  $lastname = $row['lastname']; 
  $firstname = $row['firstname']; 
  $playernumber = $row['playernumber'];

  $players .= "{ value: \"$user_key\", label: \"$playernumber $firstname $lastname\" },";

  }

/// CREATE TAGS LIST ///

$tags = ""; 

$sql = "SELECT tag, ID FROM video_feedback_taglist";

$result = $db->query($sql);

while( $row = $result->fetch_assoc()){ 
      $tag = $row['tag'];
      $ID = $row['ID'];

      $tags .= "{ value: \"$ID\", label: \"$tag\" },";
}

  
?>

  <div class="container">
    <div class="row">
     <div align="center" class="col-md-8" style="margin:0 auto; float:none;">
          <h3> Tagging Season <?= $season; ?> Game <?= $gamenumber; ?></h3>
      <div id="player"></div>
     </div>
   </div>
   <div class="row">
     <br />
     <div class="col-md-6" style="margin:0 auto; float:none;">
      
      <form method="post" id="programmer_form">
        <input type="hidden" name="season" value="<?= $season; ?>">
        <input type="hidden" name="gamenumber" value="<?= $gamenumber; ?>">
        <input type="hidden" name="embed_code" value="<?= $youtubeID; ?>">
          <div class="row">
            <div class="form-group">
              <div class="col-md-6">
                  <label>Time Start</label>   <button class="btn btn-sm btn-default timestart">Get Current Time</button>               
                  <input type="number" name="timestart" id="timestart" class="form-control" placeholder="Time Start" />
                </div>
                <div class="col-md-6">
                  <label>Time End</label>
                  <button class="btn btn-sm btn-default timeend">Get Current Time</button>
                  <input type="number" name="timeend" id="timeend" class="form-control" placeholder="Time End" />

               </div>
               
              </div>
          </div>
          <br>
			<input type="hidden" name="type" value="feedback" >

		<div class="form-group">
        <label>Title</label>
        <input type="text" name="title" id="title" class="form-control">
       </div>

		 <div class="form-group">
        <label>Comment</label>
        <textarea type="text" name="comment" id="comment" class="form-control" rows="5"></textarea>
       </div>
       <div class="form-group tags">
        <label>Action Tags</label>
        <input type="text" name="tags" id="tags" class="form-control" placeholder="Choose your tags..." />
       </div>
        <div class="form-group players">
        <label>Players Involved</label>
        <input type="text" name="players" id="players" class="form-control" placeholder="Choose your players..." />
       </div>
       <span id="success_message"></span>
       <div class="form-group">
        <input type="submit" name="submit" id="submit" class="btn btn-lg btn-block btn-success" value="Submit" />
       </div>
      </form>
      
      </div>
     </div>
    </div>
<script>
$(document).ready(function(){
 
 $('#tags').tokenfield({
  autocomplete:{
   source: [<?= $tags; ?>],
   delay:100
  },
  showAutocompleteOnFocus: true
 });

  $('#players').tokenfield({
  autocomplete:{
   source: [<?= $players; ?>],
   delay:100
  },
  showAutocompleteOnFocus: true
 });

 $('#programmer_form').on('submit', function(event){
  event.preventDefault();
  if($.trim($('#timestart').val()).length == 0)
  {
   alert("Please Enter a Time Start");
   return false;
  }
  else if($.trim($('#timeend').val()).length == 0)
  {
   alert("Please Enter a Time End");
   return false;
  }
  else if($.trim($('#tags').val()).length == 0)
  {
   alert("Please Enter At least One Action Tag");
   return false;
  }
  else if($.trim($('#players').val()).length == 0)
  {
   alert("Please Enter At least One Player");
   return false;
  }
  else
  {
   var form_data = $(this).serialize();
   $('#submit').attr("disabled","disabled");
   
   $.ajax({
    url: "./includes/handlers/video_feedback_add_handler.php",
    method: "POST",
    data: form_data,
    beforeSend:function(){
     $('#submit').val('Submitting...');
    },
    success:function(data){
     if(data != '')
     {
      $('#comment').val('');
      $('#timeend').val('');
      $('#timestart').val('');
      $('#tags').tokenfield('setTokens',[]);
      $('#players').tokenfield('setTokens',[]);
      $('#success_message').html(data);
      $('#submit').attr("disabled", false);
      $('#submit').val('Submit');
     }
    }, 
    error: function (xhr, status, error) {
          alert(xhr.responseText); 
    }
   });
   setInterval(function(){
    $('#success_message').html('');
   }, 5000);
  }
 });
 
});

  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '400',
      width: '750',
      videoId: '<?= $youtubeID; ?>'
    });
  }

$(".timestart").on("click", function(e){
  e.preventDefault();
  $('#timestart').val(Math.round(player.getCurrentTime()));    
})

$(".timeend").on("click", function(e){
  e.preventDefault();
  $('#timeend').val(Math.round(player.getCurrentTime()));    
})
      

</script>

  <?php 

} else {
  
}

 ?>


</div>

 

